//
//  CallPoliceSettingVC.m
//  sensen_ios
//
//  Created by mc on 16/4/9.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "CallPoliceSettingVC.h"

#import "ImgeLableSwitch.h"

#import "ImagesStateView.h"

#import "APIs.h"
#import "DeviceSun.h"

#import "DeviceListVC.h"

#define HEIGHT 56
#define IMAGE_HEIGHT 120

@interface CallPoliceSettingVC ()<UIPickerViewDataSource, UIPickerViewDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) UIPickerView *pickerView;
@property (strong, nonatomic) UIAlertView *tempPickerAlertView;
@property (strong, nonatomic) NSArray *pickerViewData;



@property (nonatomic, strong) UIScrollView *scrollView; // 对于iPhone4需要滑动才行
@property (nonatomic, strong) ImgeLableSwitch *waterTemperatureView;
@property (nonatomic, strong) UIView *highLowView;
@property (nonatomic, strong) ImgeLableSwitch *waterLevelView;
@property (nonatomic, strong) ImgeLableSwitch *deviceView;
@property (nonatomic, strong) UIView *imageStateView;
@property (nonatomic, strong) UISwitch *waterTemperatureSwitch;//水温报警开关
@property (nonatomic, strong) UISwitch *waterLevelSwitch;//水温报警开关
@property (nonatomic, strong) UISwitch *deviceSwitch;//设备异常开关

@property (nonatomic, strong) UIButton *highButton;
@property (nonatomic, strong) UIButton *lowButton;
@property (nonatomic, strong) ImgeLableSwitch *deviceLockView;
@property (nonatomic, strong) UISwitch *lockSwitch;//设备异常开关


@property (nonatomic, strong) ImgeLableSwitch *tempertureSetView;//鱼缸温度设置
@property (nonatomic, strong) UIButton *temperHighButton;//鱼缸加热上限温度设置

@property (nonatomic, strong) UIImageView *waterTemperatureImageView;
@property (nonatomic, strong) UIImageView *deviceImageView;
@property (nonatomic, strong) UIImageView *waterLevelImageView;

@end

@implementation CallPoliceSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设备报警设定";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self _initViews];
    self.pickerView.delegate = self;
}

#pragma mark - 创建视图
- (void)_initViews {
    [self _initScrollView];
    [self _initSetWaterTemperatureView];
    [self _initWaterTemperatureView];
    [self _inithighLowView];
}
- (void)_initScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    
    if (SCREEN_HEIGHT < 667) {
        _scrollView.contentSize = CGSizeMake(0, _scrollView.height + (667 - SCREEN_HEIGHT) + 10);
    } else {
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }
    
    [self.view addSubview:_scrollView];
}


#pragma mark - 鱼缸温度设置 高温设置
- (void)_initSetWaterTemperatureView{
    self.tempertureSetView = [[ImgeLableSwitch alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT)];
    [_scrollView addSubview:self.tempertureSetView];
    self.tempertureSetView.imageString = @"高温设定";
    self.tempertureSetView.title = @"鱼缸温度设置";
    self.tempertureSetView.Switch.hidden = YES;
    
    
    
    
    //高温按钮
    self.temperHighButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tempertureSetView addSubview:self.temperHighButton];
    [self.temperHighButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.tempertureSetView.mas_centerY);
        make.right.equalTo(self.tempertureSetView).offset(-8);
        make.size.mas_equalTo(CGSizeMake(50, 20));
    }];
    
    [self.temperHighButton setTitleColor:rgba(0, 140, 210, 1) forState:UIControlStateNormal];
    
    DeviceSun * device = [DeviceSun defaultDevice];
    
    if (device.highTemperature > 40) {
        device.highTemperature = 40;
    }else if (device.highTemperature < 0){
        device.highTemperature = 0;
    }

    
    [self.temperHighButton setTitle:[NSString stringWithFormat:@"%d度", device.highTemperature] forState:UIControlStateNormal];
    [self.temperHighButton addTarget:self action:@selector(temperHighButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - 高温设置行为   需要真实数据
- (void)temperHighButtonAction:(UIButton *)button{
    
    DeviceSun * device = [DeviceSun defaultDevice];
    
    if (device.highTemperature > 40) {
        device.highTemperature = 29;
    }else if (device.highTemperature < 0){
        device.highTemperature = 29;
    }
    
    [self.pickerView selectRow:device.highTemperature inComponent:0 animated:YES];
    [self.tempPickerAlertView setTitle:@"鱼缸加热上限温度设置"];
    [self.tempPickerAlertView setTag:2];
    [self.tempPickerAlertView show];
    
    
}




//水温报警设定
- (void)_initWaterTemperatureView{
    self.waterTemperatureView = [[ImgeLableSwitch alloc] initWithFrame:CGRectMake(0, HEIGHT, SCREEN_WIDTH, HEIGHT)];
    [_scrollView addSubview:self.waterTemperatureView];
    self.waterTemperatureView.imageString = @"设定_07";
    self.waterTemperatureView.title = @"水温报警设定";
    self.waterTemperatureSwitch = self.waterTemperatureView.Switch;
    self.waterTemperatureSwitch.enabled = YES;
    self.waterTemperatureView.Switch.on = _deviceInfo.is_temperature_on;
    [self.waterTemperatureSwitch addTarget:self action:@selector(waterTemperatureSwitchAction:) forControlEvents:UIControlEventValueChanged];
    
    
    
    //水温报警警告图片
    self.waterTemperatureImageView = [[UIImageView alloc] initWithFrame:CGRectMake(164, (HEIGHT - 20) / 2 , 20, 20)];
    [self.waterTemperatureView addSubview:self.waterTemperatureImageView];
    self.waterTemperatureImageView.image = [UIImage imageNamed:@"设备报警设定_06"];
    DeviceSun * device = [DeviceSun defaultDevice];
    NSLog(@"%d high = %d low = %d", device.waterTemperature , device.high, device.low );
    
    if (device.temperature > device.high || device.temperature < device.low) {
        self.waterTemperatureImageView.hidden = NO;
    }else{
        self.waterTemperatureImageView.hidden = YES;
    }
    
}
//水温订阅状态修改
- (void)waterTemperatureSwitchAction:(UISwitch *)waterSwitch{
    
    [SVProgressHUD showWithStatus:@"温度订阅状态修改中..." maskType:SVProgressHUDMaskTypeBlack];
    [self updateSubsribeToken:^{
        DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
                    DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
                    [deviceInfo setIs_temperature_on:waterSwitch.on];
        
                    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                    NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
                    [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
                    [userDefaults synchronize];
                    _deviceInfo.is_temperature_on = waterSwitch.on;
                    [SVProgressHUD showSuccessWithStatus:@"温度订阅状态修改成功" withDuration:1];

    } failure:^(NSInteger errorCode) {
        
        [self updateSubsribeToken:^{
            DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
            DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
            [deviceInfo setIs_temperature_on:waterSwitch.on];
            
            NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
            NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
            [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
            [userDefaults synchronize];
            _deviceInfo.is_temperature_on = waterSwitch.on;
            [SVProgressHUD showSuccessWithStatus:@"温度订阅状态修改成功" withDuration:1];
            
        } failure:^(NSInteger errorCode) {
            waterSwitch.on = !waterSwitch.on;
            [SVProgressHUD showErrorWithStatus:@"温度订阅状态修改失败,请重试" withDuration:3];
        }];
    }];
}



//高低温报警
- (void)_inithighLowView{
    self.highLowView = [[UIView alloc] initWithFrame:CGRectMake(0, self.waterTemperatureView.bottom, SCREEN_WIDTH, HEIGHT)];
    self.highLowView.backgroundColor = rgba(238, 239, 240, 1);
    [_scrollView addSubview:self.highLowView];
    
    
    UILabel * lable = [[UILabel alloc] init];
    [self.highLowView addSubview:lable];
    lable.backgroundColor = [UIColor grayColor];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.highLowView.mas_centerY);
        make.centerX.equalTo(self.highLowView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(0.5, HEIGHT / 2));
    }];
    
    
    UILabel * high = [[UILabel alloc] init];
    UILabel * low  = [[UILabel alloc] init];
    [self.highLowView addSubview:high];
    [self.highLowView addSubview:low];
    
    
    high.text = @"高温报警";
    low.text = @"低温报警";
    
    high.font = [UIFont systemFontOfSize:17];
    low.font  = [UIFont systemFontOfSize:17];
    
    
    [high mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.highLowView.mas_centerY);
        make.left.equalTo(self.highLowView.mas_left).offset(SCREEN_WIDTH / 10);
        make.size.mas_equalTo(CGSizeMake([high.text getSizeOfString:17].width+10, 20));
    }];
    
    [low mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.highLowView.mas_centerY);
        make.left.equalTo(lable.mas_right).offset(SCREEN_WIDTH / 10);
        make.size.mas_equalTo(CGSizeMake([high.text getSizeOfString:17].width+10, 20));
    }];

    
    high.textColor = [UIColor grayColor];
    low.textColor = [UIColor grayColor];
    
    self.lowButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.highButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.highLowView addSubview:self.lowButton];
    [self.highLowView addSubview:self.highButton];
    
    
    [self.highButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.highLowView.mas_centerY);
        make.left.equalTo(high.mas_right).offset(2);
        make.size.mas_equalTo(CGSizeMake(50, 20));
    }];
    
    [self.lowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.highLowView.mas_centerY);
        make.left.equalTo(low.mas_right).offset(2);
        make.size.mas_equalTo(CGSizeMake(50, 20));
    }];
    
    
    [self.highButton setTitle:@"0度" forState:UIControlStateNormal];
    [self.lowButton setTitle:@"0度" forState:UIControlStateNormal];

    [self.highButton setTitleColor:rgba(0, 140, 210, 1) forState:UIControlStateNormal];
    [self.lowButton setTitleColor:rgba(0, 140, 210, 1) forState:UIControlStateNormal];
    
    
    
    self.waterLevelView = [[ImgeLableSwitch alloc] initWithFrame:CGRectMake(0, self.highLowView.bottom, SCREEN_WIDTH, HEIGHT)];
    [self.scrollView addSubview:self.waterLevelView];
    self.waterLevelView.title = @"水位报警设定";
    self.waterLevelView.imageString = @"设定_11";
    
    self.waterLevelSwitch = self.waterLevelView.Switch;
    self.waterLevelSwitch.enabled = YES;
    self.waterLevelView.Switch.on = _deviceInfo.is_level_on;
    [self.waterLevelSwitch addTarget:self action:@selector(waterLevelSwitchAction:) forControlEvents:UIControlEventValueChanged];
    
    DeviceSun * device = [DeviceSun defaultDevice];
    //水位异常警告图片
    self.waterLevelImageView = [[UIImageView alloc] initWithFrame:CGRectMake(164, (HEIGHT - 20) / 2 , 20, 20)];
    [self.waterLevelView addSubview:self.waterLevelImageView];
    self.waterLevelImageView.image = [UIImage imageNamed:@"设备报警设定_06"];
    if (device.waterLevel > 0) {
        self.waterLevelImageView.hidden = NO;
    }else{
        self.waterLevelImageView.hidden = YES;
    }

    

    
    self.deviceView = [[ImgeLableSwitch alloc] initWithFrame:CGRectMake(0, self.waterLevelView.bottom, SCREEN_WIDTH, HEIGHT)];
    [self.scrollView addSubview:self.deviceView];
    self.deviceView.title = @"设备异常报警";
    self.deviceView.imageString = @"设定_14";
    self.deviceSwitch = self.deviceView.Switch;
    self.deviceSwitch.enabled = YES;
    self.deviceView.Switch.on = _deviceInfo.is_load_on;
    [self.deviceSwitch addTarget:self action:@selector(deviceSwitchAction:) forControlEvents:UIControlEventValueChanged];
    
    NSInteger interval = 10;
    NSInteger width = (SCREEN_WIDTH - 8 * interval) / 4;
    
    ImagesStateView * imagesView = [[ImagesStateView alloc] initWithFrame:CGRectMake(0, self.deviceView.bottom, SCREEN_WIDTH, width + interval * 4)];
    [self.scrollView addSubview:imagesView];
    
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:1];
    [array addObject:[NSNumber numberWithInt:device.floodlight]];
    [array addObject:[NSNumber numberWithInt:device.waterPump]];
    [array addObject:[NSNumber numberWithInt:device.lamp]];
    [array addObject:[NSNumber numberWithInt:device.standbyPower]];
    
     imagesView.stateArray = array;
    
    
    //设备异常警告图片
    self.deviceImageView = [[UIImageView alloc] initWithFrame:CGRectMake(164, (HEIGHT - 20) / 2 , 20, 20)];
    [self.deviceView addSubview:self.deviceImageView];
    self.deviceImageView.image = [UIImage imageNamed:@"设备报警设定_06"];
    if ([self isShowDeviceImageView:array]) {
        self.deviceImageView.hidden = NO;
    }else{
        self.deviceImageView.hidden = YES;
    }

    
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, imagesView.bottom, SCREEN_WIDTH, 60)];
    view.backgroundColor = rgba(226, 227, 228, 1);
    [self.scrollView addSubview:view];
    
    UILabel * lable3 = [[UILabel alloc] init];
    [view addSubview:lable3];
    [lable3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view.mas_centerY);
        make.centerX.equalTo(view.mas_centerX);
        make.left.equalTo(view).offset(50);
        make.right.equalTo(view).offset(-50);
        make.top.equalTo(view).offset(10);
        make.bottom.equalTo(view).offset(-10);
    }];
    
    lable3.textColor = [UIColor grayColor];
    lable3.text = @"当设备出现停电或运转异常时，本客户端将提供报警信息，请及时排除，以免造成损失";
    lable3.font = [UIFont systemFontOfSize:12];
    lable3.numberOfLines = 2;
    
    
    self.deviceLockView = [[ImgeLableSwitch alloc] initWithFrame:CGRectMake(0, view.bottom, SCREEN_WIDTH, HEIGHT)];
    [self.scrollView addSubview:self.deviceLockView];
    self.deviceLockView.title = @"设备锁定";
    self.deviceLockView.imageString = @"设定_35";
    self.lockSwitch = self.deviceLockView.Switch;
    [self.lockSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    //self.lockSwitch.enabled = NO;
    
    
    UILabel * lable6 = [[UILabel alloc] init];
    [self.deviceLockView addSubview:lable6];
    [lable6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.deviceLockView.mas_centerY);
        make.right.equalTo(self.deviceLockView.Switch.mas_left).offset(-8);
        make.size.mas_equalTo(CGSizeMake(150, 20));
    }];
    
    lable6.textColor = [UIColor blackColor];
    lable6.text = @"防止其他客户端误测";
    lable6.font = [UIFont systemFontOfSize:13];
    lable6.numberOfLines = 1;
    lable6.textAlignment = NSTextAlignmentRight;
    
    
    
    UIView * view1 = [[UIView alloc] initWithFrame:CGRectMake(0, self.deviceLockView.bottom, SCREEN_WIDTH, 50)];
    view1 .backgroundColor = rgba(226, 227, 228, 1);
    [self.scrollView addSubview:view1];
    
    UILabel * lable4 = [[UILabel alloc] init];
    [view1 addSubview:lable4];
    [lable4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view1 .mas_centerY);
        make.centerX.equalTo(view1 .mas_centerX);
        make.left.equalTo(view1).offset(50);
        make.right.equalTo(view1).offset(-50);
        make.top.equalTo(view1).offset(5);
        make.bottom.equalTo(view1).offset(-5);
    }];
    
    lable4.textColor = [UIColor grayColor];
    lable4.text = [NSString stringWithFormat:@"经销商查询请登录森森官网\nhttp://www.sunsuncn.com/"];
    lable4.font = [UIFont systemFontOfSize:13];
    lable4.numberOfLines = 2;
    lable4.textAlignment = NSTextAlignmentCenter;

    CGFloat hei;
    if (SCREEN_HEIGHT < 667) {
        hei = 667 + 10;
    }else{
        hei = SCREEN_HEIGHT + 64;
    }
    CGFloat hei2 = hei - view1.bottom  - 64;
    

    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, view1.bottom, SCREEN_WIDTH, hei2)];
    footer.backgroundColor = rgba(237, 238, 239, 1);
    [self.scrollView addSubview:footer];
    

    // 创建确定按钮
    UIButton  * determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:determineBtn];
    [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
    [determineBtn addTarget:self action:@selector(determineAction:) forControlEvents:UIControlEventTouchUpInside];
    [determineBtn setBackgroundColor:SS_DEVICE_BLUE_COLOR];
    determineBtn.layer.borderColor = SS_DEVICE_BLUE_COLOR.CGColor;
    determineBtn.layer.borderWidth = 1;
    determineBtn.layer.masksToBounds = YES;
    determineBtn.layer.cornerRadius = 3.0;
    
    
    // 创建取消按钮
    UIButton  * cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTintColor:[UIColor blackColor]];
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setBackgroundColor:[UIColor clearColor]];
    cancelBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cancelBtn.layer.borderWidth = 1;
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.cornerRadius = 3.0;
    
    [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footer).offset(50);
        make.centerY.equalTo(footer.mas_centerY);
        make.height.equalTo(@30);
        make.height.equalTo(cancelBtn);
        make.right.equalTo(cancelBtn.mas_left).offset(-20);
        make.width.equalTo(cancelBtn);
    }];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(footer).offset(-50);
        make.centerY.equalTo(footer.mas_centerY);
        make.height.equalTo(@30);
        
    }];
    
    
    UILabel * lable5 = [[UILabel alloc] init];
    [footer addSubview:lable5];
    [lable5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footer).offset(50);
        make.right.equalTo(footer).offset(-50);
        make.top.equalTo(footer).offset(10);
        make.bottom.equalTo(determineBtn.mas_top).offset(-10);
    }];
    
    lable5.textColor = [UIColor blackColor];
    lable5.text = @"注意：本功能仅使用于具备报警装置的监控系统";
    lable5.font = [UIFont systemFontOfSize:13];
    lable5.numberOfLines = 1;
    
    [self _setData];
}



//是否需要显示设备异常警告按钮
- (BOOL)isShowDeviceImageView:(NSMutableArray *)stateArray{
    for (NSNumber *number in stateArray) {
        if ([number integerValue] > 0) {
            return YES;
        }
    }
    return NO;
}


//水位订阅开关更改
- (void)waterLevelSwitchAction:(UISwitch *)levelSwitch{
    
        [SVProgressHUD showWithStatus:@"水位订阅状态修改中..." maskType:SVProgressHUDMaskTypeBlack];
    
        [self updateSubsribeToken:^{
                        DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
                        DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
                        [deviceInfo setIs_level_on:levelSwitch.on];
                        [deviceListVC.tableView reloadData];
            
            
                        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                        NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
                        [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
                        [userDefaults synchronize];
            
                        _deviceInfo.is_level_on = levelSwitch.on;
                        [SVProgressHUD showSuccessWithStatus:@"水位订阅状态修改成功" withDuration:1];

        } failure:^(NSInteger errorCode) {

            
            [self updateSubsribeToken:^{
                DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
                DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
                [deviceInfo setIs_level_on:levelSwitch.on];
                [deviceListVC.tableView reloadData];
                
                
                NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
                [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ];//存储设备列表
                [userDefaults synchronize];
                
                _deviceInfo.is_level_on = levelSwitch.on;
                [SVProgressHUD showSuccessWithStatus:@"水位订阅状态修改成功" withDuration:1];
                
            } failure:^(NSInteger errorCode) {
                levelSwitch.on = !levelSwitch.on;
                [SVProgressHUD showErrorWithStatus:@"水位订阅状态修改失败,请重试" withDuration:3];
                
            }];
            
        }];
}


//设备异常报警订阅状态修改
- (void)deviceSwitchAction:(UISwitch *)deviceSwitch{
    
            [SVProgressHUD showWithStatus:@"设备异常报警订阅状态修改中..." maskType:SVProgressHUDMaskTypeBlack];
            [self updateSubsribeToken:^{
                
                DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
                DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
                [deviceInfo setIs_load_on:deviceSwitch.on];
                [deviceListVC.tableView reloadData];
                NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
                [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ ];//存储设备列表
                [userDefaults synchronize];
                _deviceInfo.is_load_on = deviceSwitch.on;
                [SVProgressHUD showSuccessWithStatus:@"设备异常报警订阅状态修改成功" withDuration:1];

            } failure:^(NSInteger errorCode) {

                [self updateSubsribeToken:^{
                    DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
                    DeviceInfo *deviceInfo = [deviceListVC.deviceList objectAtIndex:_deviceInfo.indexPath.section];
                    [deviceInfo setIs_load_on:deviceSwitch.on];
                    [deviceListVC.tableView reloadData];
    
                    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                    NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:deviceListVC.deviceList];
                    [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ ];//存储设备列表
                    [userDefaults synchronize];
                    _deviceInfo.is_load_on = deviceSwitch.on;
                    [SVProgressHUD showSuccessWithStatus:@"设备异常报警订阅状态修改成功" withDuration:1];
                    
                } failure:^(NSInteger errorCode) {
                    deviceSwitch.on = !deviceSwitch.on;
                    [SVProgressHUD showErrorWithStatus:@"设备异常报警订阅状态修改失败,请重试" withDuration:3];
                    
                }];
                
            }];
}




//数据设置  仅AQ805可以设置水温高低阙值设置和有关推送按钮支持
- (void)_setData{
    DeviceSun * device = [DeviceSun defaultDevice];
    
    if (device.high > 40) {
        device.high = 40;
    }else if (device.high < 0){
        device.high = 0;
    }
    
    if (device.low > 40) {
        device.low = 0;
    }else if (device.low < 0){
        device.low = 0;
    }
    //高温报警温度
    [self.highButton setTitle:[NSString stringWithFormat:@"%d度", device.high] forState:UIControlStateNormal];
    //低温报警温度
    [self.lowButton setTitle:[NSString stringWithFormat:@"%d度", device.low] forState:UIControlStateNormal];
    
    [self.highButton addTarget:self action:@selector(highTempButtonpressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.lowButton addTarget:self action:@selector(lowTempButtonpressed:) forControlEvents:UIControlEventTouchUpInside];
    self.highButton.enabled = NO;
    self.lowButton.enabled = NO;
    //仅AQ805可以设置水温高低阙值设置和有关推送按钮支持
    if (device.version == AQ805) {
        self.highButton.enabled = YES;
        self.lowButton.enabled = YES;
    }else{
        self.waterTemperatureSwitch.on = NO;
        self.waterTemperatureSwitch.enabled = NO;
        self.waterLevelSwitch.on = NO;
        self.waterLevelSwitch.enabled = NO;
        self.deviceSwitch.on = NO;
        self.deviceSwitch.enabled  = NO;
    }
    
    
    //带功率设备关闭鱼缸水温设置
    if (device.version == AQ211) {
        self.temperHighButton.userInteractionEnabled = NO;
    }

    
    
    //锁定状态
     if (device.lock > 0) {
        self.lockSwitch.on = YES;
    }else{
        self.lockSwitch.on = NO;
    }
}



#pragma -mark- 锁定按钮
- (void)switchAction:(UISwitch *)deviceSwitch{
    NSLog(@"开关的状态  ＝ %d", deviceSwitch.on);
    //DeviceSun * device = [DeviceSun defaultDevice];
    self.lockSwitch.on = deviceSwitch.on;
    //设备锁定
    [[APIs sharedInstance] deviceLockOrUnlockWithpassword:_deviceInfo.password LockOStatus:deviceSwitch.on success:^(BOOL status) {
//        if (status) {
//            self.lockSwitch.on = YES;
//             device.lock = 1;
//        }else{
//            self.lockSwitch.on = NO;
//             device.lock = 0;
//        }
        
    } interupted:^(NSInteger errorCode) {
               
        self.lockSwitch.on = deviceSwitch.on;
    }];
    
}



#pragma -mark- 确定与取消 行为
//确定
- (void)determineAction:(UIButton *)button{
    NSLog(@"确定");
    [self.navigationController popViewControllerAnimated:YES];
}



//取消
- (void)cancelAction:(UIButton *)button{
    NSLog(@"取消");
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma -mark- Actions
- (void)highTempButtonpressed:(id)sender
{
    DeviceSun * device = [DeviceSun defaultDevice];
    if (device.high > 40) {
        device.high = 40;
    }else if (device.high < 0){
        device.high = 0;
    }
    [self.pickerView selectRow:device.high inComponent:0 animated:YES];
    [self.tempPickerAlertView setTitle:@"高温报警设置"];
    [self.tempPickerAlertView setTag:0];
    [self.tempPickerAlertView show];
}

- (void)lowTempButtonpressed:(id)sender
{
    DeviceSun * device = [DeviceSun defaultDevice];
    if (device.low > 40) {
        device.low = 40;
    }else if (device.low < 0){
        device.low = 0;
    }
    [self.pickerView selectRow:device.low inComponent:0 animated:YES];
    [self.tempPickerAlertView setTitle:@"低温报警设置"];
    [self.tempPickerAlertView setTag:1];
    [self.tempPickerAlertView show];
}




#pragma -mark- Setter and Getter
-(UIAlertView *)tempPickerAlertView
{
    if (!_tempPickerAlertView)
    {
        _tempPickerAlertView = [[UIAlertView alloc] initWithTitle:@""
                                                          message:@""
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定", nil];
        [_tempPickerAlertView setValue:self.pickerView forKey:@"accessoryView"];
    }
    return _tempPickerAlertView;
}

-(NSArray *)pickerViewData
{
    if (!_pickerViewData)
    {
        _pickerViewData = @[@"0",@"1",@"2",@"3",@"4",
                            @"5",@"6",@"7",@"8",@"9",
                            @"10",@"11",@"12",@"13",@"14",
                            @"15",@"16",@"17",@"18",@"19",
                            @"20",@"21",@"22",@"23",@"24",
                            @"25",@"26",@"27",@"28",@"29",
                            @"30",@"31",@"32",@"33",@"34",
                            @"35",@"36",@"37",@"38",@"39",@"40"];
    }
    return _pickerViewData;
}

-(UIPickerView *)pickerView
{
    if (!_pickerView)
    {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(10, 0, 70, 100)];
        [_pickerView setDataSource:self];
        [_pickerView setDelegate:self];
    }
    return _pickerView;
}
#pragma -mark- UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.pickerViewData count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = [self.pickerViewData objectAtIndex:row];
    title = [title stringByAppendingString:@"度"];
    return title;
}

#pragma -mark- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView isEqual:self.tempPickerAlertView])
    {
        if (1 == buttonIndex)
        {
            switch (self.tempPickerAlertView.tag)
            {
                case 0:{
                    DeviceSun * device = [DeviceSun defaultDevice];
                    NSString *lowTitle = [NSString stringWithFormat:@"%d",device.low];
                    if ((long)[self.pickerView selectedRowInComponent:0] < [lowTitle integerValue]) {
                        [SVProgressHUD showErrorWithStatus:@"高温阙值必须大于低温阙值，设置失败请重试" withDuration:1.5];
                        return;
                    }else if ((((long)[self.pickerView selectedRowInComponent:0] > [lowTitle integerValue]) || ((long)[self.pickerView selectedRowInComponent:0] == [lowTitle integerValue]))&& ((long)[self.pickerView selectedRowInComponent:0] - [lowTitle integerValue] < 2 ) ){
                        [SVProgressHUD showErrorWithStatus:@"高温阙值必须大低温阙值2摄氏度或以上，设置失败请重试" withDuration:1.5];
                        return;
                    }

                    
                    [self.highButton setTitle:[NSString stringWithFormat:@"%ld度", (long)[self.pickerView selectedRowInComponent:0]]
                                     forState:UIControlStateNormal];
                    [_tempPickerAlertView dismissWithClickedButtonIndex:1 animated:NO];
                    [SVProgressHUD showWithStatus:@"修改中..." maskType:SVProgressHUDMaskTypeBlack];
                    if(![[APIs sharedInstance] checkPPPP]){
                        //会话失效
                        [[APIs sharedInstance] reconnect:^(NSInteger session){
                            [self setFirstWaterTemperature:(NSInteger)[self.pickerView selectedRowInComponent:0]];
                        } failure:^(NSInteger errCode){
                            [SVProgressHUD showErrorWithStatus:@"设备断开连接,请重试" withDuration:3];
                        }];
                        
                    }else{
                         [self setFirstWaterTemperature:(NSInteger)[self.pickerView selectedRowInComponent:0]];
                    }

                    
                    device.high = (int)[self.pickerView selectedRowInComponent:0];
                    
                }
                    break;
                case 1:{
                    DeviceSun * device = [DeviceSun defaultDevice];
                    NSString *highTitle = [NSString stringWithFormat:@"%d",device.high];
                    
                    if ((long)[self.pickerView selectedRowInComponent:0] > [highTitle integerValue]) {
                        [SVProgressHUD showErrorWithStatus:@"低温阙值必须小于低温阙值，设置失败请重试" withDuration:1.5];
                        return;
                    }else if (((long)[self.pickerView selectedRowInComponent:0] < [highTitle integerValue] || (long)[self.pickerView selectedRowInComponent:0] == [highTitle integerValue] )&&([highTitle integerValue] - (long)[self.pickerView selectedRowInComponent:0]  < 2 ) ){
                        [SVProgressHUD showErrorWithStatus:@"低温阙值必须小低温阙值2摄氏度或以上，设置失败请重试" withDuration:1.5];
                        return;
                    }

                    
                    
                    
                    [self.lowButton setTitle:[NSString stringWithFormat:@"%ld度", (long)[self.pickerView selectedRowInComponent:0]]
                                    forState:UIControlStateNormal];
                    [_tempPickerAlertView dismissWithClickedButtonIndex:1 animated:NO];
                    [SVProgressHUD showWithStatus:@"修改中..." maskType:SVProgressHUDMaskTypeBlack];
                    if(![[APIs sharedInstance] checkPPPP]){
                        //会话失效
                        [[APIs sharedInstance] reconnect:^(NSInteger session){
                            [self setSecondWaterTemperature:(NSInteger)[self.pickerView selectedRowInComponent:0]];
                        } failure:^(NSInteger errCode){
                            [SVProgressHUD showErrorWithStatus:@"设备断开连接,请重试" withDuration:3];
                        }];
                        
                    }else{
                        [self setSecondWaterTemperature:(NSInteger)[self.pickerView selectedRowInComponent:0]];
                    }

                    
                    
                    device.low = (int)[self.pickerView selectedRowInComponent:0];
                }
                    break;
                    
                    
                case 2:{
                    
                    DeviceSun * device = [DeviceSun defaultDevice];
//                    NSLog(@"高温设置");
                    
                    UINT16 temp = (UINT16)[self.pickerView selectedRowInComponent:0];
                    temp = temp * 10;
                    
                    [self.temperHighButton setTitle:[NSString stringWithFormat:@"%ld度", (long)[self.pickerView selectedRowInComponent:0]]
                                           forState:UIControlStateNormal];
                    [_tempPickerAlertView dismissWithClickedButtonIndex:1 animated:NO];
                    [SVProgressHUD showWithStatus:@"修改中..." maskType:SVProgressHUDMaskTypeBlack];
                    if(![[APIs sharedInstance] checkPPPP]){
                        //会话失效
                        [[APIs sharedInstance] reconnect:^(NSInteger session){
                            [self setThirdWaterTemperature:temp];
                        } failure:^(NSInteger errCode){
                            [SVProgressHUD showErrorWithStatus:@"设备断开连接,请重试" withDuration:3];
                        }];
                        
                    }else{
                        [self setThirdWaterTemperature:temp];
                    }

                    
                   device.highTemperature = (int)[self.pickerView selectedRowInComponent:0];
                    
                    }
                    break;
     
                    
                default:
                    break;
            }
        }
    }
}



-(void)setFirstWaterTemperature:(NSInteger )index{
    
    DeviceSun * device = [DeviceSun defaultDevice];
    [[APIs sharedInstance] setHighOrLowTemperatureWithHigh:index low:device.low password:device.password success:^{
        NSLog(@"setHighOrLowTemperatureWithHigh Success 0");
        device.high = (int)[self.pickerView selectedRowInComponent:0];
        if (device.temperature > device.high || device.temperature < device.low) {
            self.waterTemperatureImageView.hidden = NO;
        }else{
            self.waterTemperatureImageView.hidden = YES;
        }
        [SVProgressHUD showSuccessWithStatus:@"设置成功" withDuration:1];
        
    } failure:^(NSInteger errorCode) {
        NSLog(@"setHighOrLowTemperatureWithHigh errorCode 0");
        [SVProgressHUD dismiss];

    }];

    
}


-(void)setSecondWaterTemperature:(NSInteger )index{
    
    DeviceSun * device = [DeviceSun defaultDevice];
    
    [[APIs sharedInstance] setHighOrLowTemperatureWithHigh:device.high low:index password:device.password success:^{
        NSLog(@"setHighOrLowTemperatureWithHigh Success 1");
        [SVProgressHUD showSuccessWithStatus:@"设置成功" withDuration:1];
        device.low = (int)[self.pickerView selectedRowInComponent:0];
        if (device.temperature > device.high || device.temperature < device.low) {
            self.waterTemperatureImageView.hidden = NO;
        }else{
            self.waterTemperatureImageView.hidden = YES;
        }
        
        
    } failure:^(NSInteger errorCode) {
        NSLog(@"setHighOrLowTemperatureWithHigh errorCode 1");
         [SVProgressHUD dismiss];
    }];

    
}


-(void)setThirdWaterTemperature:(NSInteger )index{
    
    [[APIs sharedInstance] setTemperature:index password:_deviceInfo.password success:^(){
        NSLog(@"设置成功");
        [SVProgressHUD showSuccessWithStatus:@"设置成功" withDuration:1];
    }interupted:^(NSInteger errCode){
        [SVProgressHUD dismiss];
    }];

    
    
}




//更新订阅Token
-(void) updateSubsribeToken:(void (^)())success
                      failure:(void (^)(NSInteger errorCode))failure;
{
    
        [DeviceControlVC updateSubscribeToken:self.deviceInfo success:^(NSNumber *loadSubID ,NSNumber *  levelSubID ,NSNumber * tempSubID){
            NSLog(@"updateSubscribeToken success");
            success();
            
        } interupted:^(NSInteger errCode){
            NSLog(@"updateSubscribeToken error");
            failure(errCode);
            
            
        }];
        
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
